$(function() {

    var TOTAL_WORD_COUNT = 140;

	function loadComments() {
        var d = $.Deferred();
        gCommentListViewConfig['defer'] = d;
        d.done(function(data) {
            if(data) {
                $('.J-comment-count').text(data.total_number||0);
            }
        }).always(function() {
            regLoadMoreEvent('comment-listview', 'loadmore-comments', gCommentListViewConfig);
            if(location.hash == '#to-comments') {
                location.hash = 'comments';
            }
        });
        listener.trigger('com.neihanshequ', 'comment-listview', 'loadcomments', gCommentListViewConfig);
    }

    function _getCommentID(data) {
    	var p = 'comment_id';
    	var idx = data.indexOf(p);
    	var idxEnd = data.indexOf(' ', idx+p.length);
    	var commentId = data.substring(idx+p.length, idxEnd);
    	commentId = commentId.replace('=', '').replace(/"/g, '');
    	return commentId;
    }

    var commonUpdatePlatform = window.updatePlatform;

    function updatePlatform(p) {
        var selector = $('#syncToPlatformSelector');
        commonUpdatePlatform(selector, p);
    }

    function updateRemainCount() {
        var $t = $('#text');
        var value = $t.val();
        var count = value.length;
        var remain = TOTAL_WORD_COUNT - count;
        $('.words-remain-wrapper .words').text(remain);
    }

    function updateNextItem($el, gid) {
        if(gid > 0) {
            $el.attr('href', '/p'+gid+'/').show();
        }else {
            $el.parents('.next-item').hide();
        }
    }    

	function init() {
		loadComments();

        var platformStr = getCurrentUser().platform || '[]';
        var platform = JSON.parse(platformStr);
        updatePlatform(platform);

        listener.on('com.neihanshequ.user', 'change', function(type, user) {
            user = user || {};
            var avatar = user.avatar_url || '//s3a.bytecdn.cn/neihan/resource/neihan_web/static/image/site-v2/default-me_3c7ec40.png';
            $('#currentUserAvatar').attr('src', avatar);

            var platform = user.platform || [];
            updatePlatform(platform);


        });

        $('#syncToPlatformSelector li').click(function(event) {
            if(!checkUserLogin()) {
                return false;
            }
            var $ct = $(event.currentTarget);
            var type = $ct.data('type');
            var platformList = getPlatform();
            if($.inArray(type, platformList) != -1) {
                if($ct.hasClass('selected')) {
                    $ct.removeClass('selected');
                }else {
                    $ct.addClass('selected');
                }
            }else {
                CommonUserUtil.loginByOther(type, {
                    openWindow: true,
                    successCb: function(user) {
                        var platform = user.platform;
                        updatePlatform(platform);
                    }
                });
            }
        });

        $('#postCommentForm').submit(function(){
            if(!checkUserLogin()) {
                return false;
            }
        	var self = this;
            var v = $('#text').val();
            if(v.length > TOTAL_WORD_COUNT) {
                listener.trigger('com.neihanshequ', 'popupTip', 
                    {text:'您写的太多啦，字数上限是'+TOTAL_WORD_COUNT+'哦！'}
                );
                return false;
            }
            v = $.trim(v);
            if(!v.length) {
                listener.trigger('com.neihanshequ', 'popupTip', {text:'评论内容不能为空'});
                return false;
            }
            var selectedPlatform = $('#syncToPlatformSelector').find('li.selected');
            var platform = [];
            selectedPlatform.each(function(idx, p) {
                platform.push($(p).data('type'));
            });
            $(this).ajaxSubmit({
                data: {
                    platform: platform.join(',')
                },
                success: function(d) {
                	if(d.message == 'success') {
                        var replyToContent = $('#replyToCommentId').attr('data-replyToContent');
                		var commentId = _getCommentID(d.data);
	                    var time = new Date().format('yy-MM-dd hh:mm');
	                    var name = getCurrentUser().name || '';
	                    var text = $(self).find('#text').val();
	                    var $listItem = $('#tmplNode').clone(true);
	                    $listItem.find('.name').text(name);
	                    var $time = $listItem.find('.time').attr('title', +new Date());
	                    $listItem.find('p').text(text+replyToContent);
	                    $listItem.find('.options').attr('data-comment-id', commentId);
	                    $listItem.removeClass('hidden');
                        var target = $('#comments').find('.comments');
	                    target.find('.comment-list').prepend($listItem);
                        target.find('.J-comments-count').text(function(){
                            return parseInt($(this).text()) + 1;
                        });
                        $time.timeago();
                        var defaultholder = $('#text').attr('data-defaultholder');
                        $('#text').attr('placeholder', defaultholder);
                        $('#text').val('');
                        $('#replyToCommentId').val('');
                        $('#replyToCommentId').attr('data-replyToContent', '');
                	}else {
                        var tips = '';
                        if(d.message == 'error') {
                            if(d.data && d.data.description){
                                tips = d.data.description;
                            }else {
                                tips = (d.data || d.message);
                            }
                        }else {
                            tips = d.message;
                        }
                		listener.trigger('com.neihanshequ', 'popupTip', {text:tips});
                	}
                }
            });
            return false;
        });

        var eventMethod = 'input';
        if($.browser.msie && $.browser.version < 9) {
            eventMethod = 'keyup';
        }
        
        $('#text').bind(eventMethod, function(event) {
            updateRemainCount();
        }).focus(function() {
            updateRemainCount();
        });

        var nextId = -1,
            prevId = -1;
        if('gStore' in window) {
            var v = gStore.get(Constant.GROUP_ID_LIST_KEY_PREFIX);
            if(v) {
                var linkTable = null;
                try{
                    linkTable = JSON.parse(v);
                }catch(e){}
                if(linkTable) {
                    nextId = getNextGroupId(linkTable, gCommentListViewConfig.gid);
                    prevId = getPrevGroupId(linkTable, gCommentListViewConfig.gid);
                }
            }
            updateNextItem($('#prevGroupLink'), nextId);
            updateNextItem($('#nextGroupLink'), prevId);
        }

        
        
	}

	init();
});